//User模块下的vuex
import {
    reqGetCode,
    reqRegister,
    reqLogin,
    reqLogout,
    reqUserInfo,
} from "@/api";

import { setUserTokenToLocal, getUserTokenByLocal, clearUserToken } from "@/utils/uuidToken.js";

const state = {
    userToken: getUserTokenByLocal() || '',
    //存储数据
    userInfo: {},
};

const mutations = {
    //保存Token
    GETUSERTOKEN(state, userToken) {
        state.userToken = userToken;
        setUserTokenToLocal(userToken);
    },
    //获取用户信息
    GETUSERINFO(state, userInfo) {
        // Object.assign(state.userInfo,userInfo)  
        state.userInfo = userInfo;
    },
    //退出登录,清除相关信息
    LOGOUTCLEARINFO(state) {
        clearUserToken();
        state.userToken = '';
        state.userInfo = {};
    }

};

const actions = {
    //获取验证码
    async getCode({ commit }, phone) {
        let result = await reqGetCode(phone);
        if (result.code == 200) {
            return result.data;
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //注册
    async postRegister({ commit }, userInfo) {
        let result = await reqRegister(userInfo);
        if (result.code == 200) {
            return 'OK';
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //登录
    async postLogin({ commit, dispatch }, { phone, pwd }) {
        let result = await reqLogin(phone, pwd);
        if (result.code == 200) {
            commit('GETUSERTOKEN', result.data.token)
            await dispatch('getUserInfo');
            return 'OK'
        } else {
            return Promise.reject(new Error(result.message));

        }
    },
    //登出
    async postLogout({ commit }) {
        let result = await reqLogout();
        if (result.code == 200) {
            commit('LOGOUTCLEARINFO');
            return 'OK';
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //获取用户信息 
    async getUserInfo({ commit }) {
        let result = await reqUserInfo();
        if (result.code == 200) {
            commit('GETUSERINFO', result.data)
            return 'OK';
        } else {
            return Promise.reject(new Error('faile'))
        }
    },


};

const getters = {

};

export default { state, mutations, actions, getters };
